package com.example.demo.service;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.math.BigInteger;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.AbstractMap.SimpleEntry;

import it.unisa.dia.gas.jpbc.Element;
import it.unisa.dia.gas.plaf.jpbc.field.z.ZrElement;

public class Alice {

	public PubParams p;
	ProxyReEncrypt  d=new ProxyReEncrypt ();
	private List<Element> mu;
	private SimpleEntry<Map,Map> content;
	private int m,t;
	private byte[] encryptedMessage;
	final String path="D:\\java_work\\data\\";
	public Alice(PubParams p,int m,int t) {
		// TODO Auto-generated constructor stub
		this.p=p;
		this.m=m;
		this.t=t;
	}
	public void FileEncrypt(String message) {
		 ZrElement M=(ZrElement) this.p.Zr.newRandomElement();// �ԳƼ��ܵ���Կ
		 encryptedMessage=AES.encrypt(message.getBytes(),M.toBytes());
		 d.writeFile(path+"encryptedMessage",encryptedMessage);
		 content=d.Enc(this.p,M,null);//sita C
		return;
		  
	}
	public void RkGen(Element A){

		 SimpleEntry<Element,Element> rkws=d.RkGen(p,null,content.getKey(),A);//rkw_1,rkw_2
		   SimpleEntry<List<Element>,List<Element>> xsAndYs=d.getSecret((ZrElement) rkws.getValue(), m, t, p);
		   
		  for(int i=0;i<m;i++) {
			  upload(xsAndYs.getKey().get(i),xsAndYs.getValue().get(i),content.getValue(), rkws.getKey(),i);
		  }
		  return ;
	}
	private void upload(Element x, Element y, Map C, Element rkw_1,Integer index) {
		byte[] c1=(byte[])C.get("c1");
		byte[] c2=((Element)C.get("c2")).toBytes();
		byte[] c3=((Element)C.get("c3")).toBytes();
		byte[] xbyte=x.toBytes();
		byte[] ybyte=y.toBytes();
		byte[] rkw_1byte=rkw_1.toBytes();
		d.writeFile(path+"c1", c1);
		d.writeFile(path+"c2", c2);
		d.writeFile(path+"c3", c3);
		d.writeFile(path+"xbyte"+index.toString(), xbyte);
		d.writeFile(path+"ybyte"+index.toString(), ybyte);
		d.writeFile(path+"rkw_1byte", rkw_1byte);
		
	}
	public void dec() {
		byte[] m1=d.Dec1(p,content.getKey(),content.getValue());
		   System.out.println("DEC1-message:"+new BigInteger(m1).toString());
		   String message;
		try {
			message = new String(d.decrypt(encryptedMessage, new BigInteger(m1).toByteArray()));
			System.out.println(message);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
	}
	public void setReceivers(List<Element> mu){
		this.mu=mu;
	}
	public List<Element> getReceivers() {
		return this.mu;
	}
	public List<Element> readIDFromFile(String path) throws IOException, ClassNotFoundException{
    	FileInputStream freader = new FileInputStream(path);
    	ObjectInputStream objectInputStream = new ObjectInputStream(freader);
    	List<byte[]> idbyte2=(List<byte[]>) objectInputStream.readObject();
    	List<Element> id2=new LinkedList<>();
    	for(byte[] bytes:idbyte2) {
    		id2.add(p.Zr.newElementFromBytes(bytes));
    	}
    	return id2;
    	
    }
	
	
	
	

}
